<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\Record\Mapper;

use App\Record\Model\RecordPaymentNotice;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Whoops\Exception\ErrorException;

/**
 * 支付回调记录Mapper类
 */
class RecordPaymentNoticeMapper extends AbstractMapper
{
    /**
     * @var RecordPaymentNotice
     */
    public $model;

    public function assignModel()
    {
        $this->model = RecordPaymentNotice::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {

        // ID
        if (isset($params['id']) && filled($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 订单号
        if (isset($params['order_sn']) && filled($params['order_sn'])) {
            $query->where('order_sn', '=', $params['order_sn']);
        }

        // 通知报文
        if (isset($params['text']) && filled($params['text'])) {
            $query->where('text', '=', $params['text']);
        }

        // 通知处理状态 0 待处理 1 已处理
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 
        if (isset($params['create_time']) && filled($params['create_time'])) {
            $query->where('create_time', '=', $params['create_time']);
        }

        // 
        if (isset($params['update_time']) && filled($params['update_time'])) {
            $query->where('update_time', '=', $params['update_time']);
        }

        return $query;
    }

    public function sendNotice($params)
    {
        $orderInfo = \App\Record\Model\RecordPaymentOrder::query()->where('order_sn', $params['order_sn'])->first();
        if (empty($orderInfo)) {
            throw new ErrorException(t('code.pay_notice_order_empty'));
        }
        $methodId = $orderInfo->method_id;
        $methodInfo = \App\Payment\Model\PaymentMethod::query()->where('id', $methodId)->first();
        if (empty($methodInfo)) {
            throw new ErrorException(t('code.pay_method_empty'));
        }
        $payNoticeUrl = $methodInfo['setting']['notify_url'];
        //请求支付回调
        \App\Lib\Library\RequestLibrary::requestPostResultJsonData($payNoticeUrl, json_decode($params['text']));
        return $params;
    }
}